package models

import (
	"fmt"
	"github.com/fantomo/go-iching/utils/mysql"
	"time"
)

// BaseModel 基本结构
type BaseModel struct {
	ID          int64     `gorm:"column:id;type:bigint;primaryKey;autoIncrement" json:"id,string"`
	CreatedTime time.Time `gorm:"column:created_time;type:datetime;default=time.Now()" json:"createdTime" example:"2023-01-19T01:06:02+08:00"`
	UpdatedTime time.Time `gorm:"column:updated_time;type:datetime;default=time.Now()" json:"updatedTime" example:"2023-01-19T01:06:02+08:00"`
	Deleted     bool      `gorm:"column:deleted;default:false" json:"-"`
}

// Pagination 分页数据
func Pagination(currPage, pageSize int, model interface{}, sql ...string) (data interface{}) {
	var count int64
	if currPage <= 0 {
		currPage = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}
	offset := (currPage - 1) * pageSize

	if len(sql) > 0 {
		fmt.Println("sql: ", sql[0])
		mysql.DB.Model(model).Where(sql[0]).Count(&count)
		mysql.DB.Offset(offset).Limit(pageSize).Where(sql[0]).Order("id DESC").Find(model)
	} else {
		mysql.DB.Model(model).Where("deleted = 0").Count(&count)
		mysql.DB.Offset(offset).Limit(pageSize).Where("deleted = 0").Order("id DESC").Find(model)
	}
	data = map[string]interface{}{
		"count": count,
		"list":  &model,
	}
	return data
}
